/**
 * Created by wanchao on 2017/4/5.
 */
import config from '../config/index'
import helper from './helper'
import md5 from 'md5'
import {Base64} from 'js-base64'
import errCodeHelper from './errCodeHelper'

var http = {
    // post方式访问api
    post (url, data, success, error) {
        http.ajax('POST', url, data, success, error)
    },
    // get方式访问api
    get (url, data, success, error) {
        http.ajax('GET', url, data, success, error)
    },
    // put方式访问api
    put (url, data, success, error) {
        http.ajax('PUT', url, data, success, error)
    },
    // delete方式访问api
    delete (url, data, success, error) {
        http.ajax('DELETE', url, data, success, error)
    },
    ajax (type, url, data, success, error) {
        // 拼接url
        if(!/^http/.test(url)) url = config.site.apiRoot + url;

        // 数据处理, 转成json字符串
        if(typeof(data) == 'object' && type != 'GET') data = window.JSON.stringify(data)

        // 头信息
        let token = helper.localStorage('token') // 从本地存储里读取
        let salt = parseInt( new Date().getTime() / 1000 )
        let sign = Base64.encode( md5(token+salt) );
        let headers = {"ts": salt, "token": token, "sign": sign}

        // console.log(data,headers)
        // 发请求
        window.Dom7.ajax({
            type: type,
            url: url,
            data: data,
            dataType: 'json',
            headers: headers,
            success (data, status, xhr) {
                errCodeHelper.errCode(data.Code);
                if (!data.hasOwnProperty('Code') || data.Code == 0) {
                    if (success) success(data)
                } else {
                    console.log('error');
                    // errCodeHelper.errCode(data.Code);
                    if (error) error(data)
                }
            },
            error (xhr, status) {
                if (error) error({code: -1, msg: ''})
            }
        })
    }
}

export default http